<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 5px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      max-height="600px"
    >
      <el-table-column label="ID" prop="id" align="center" />
      <el-table-column label="角色" prop="roleName" align="center" />
      <el-table-column label="标识" prop="tag" align="center" />
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button-group>
            <el-button type="primary" size="mini" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" size="mini" @click="handleAssign(row)">
              分配权限
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="角色" prop="roleName" required>
          <el-input v-model="temp.roleName" />
        </el-form-item>
        <el-form-item label="标识" prop="tag" required>
          <el-input v-model="temp.tag" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="dialogRolesVisible" :before-close="handleClose">
      <el-tree
        ref="ruleTree"
        :data="ruleList"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectRuleList"
        :props="defaultProps"
        default-expand-all
        :check-strictly="true"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRolesVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="assignRules">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'List',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        status: undefined
      },
      temp: {
        id: undefined,
        roleName: '',
        tag: ''
      },
      rules: {
        roleName: [{ required: true, message: '角色必填', trigger: 'blur' }],
        tag: [{ required: true, message: '标识必填', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑角色',
        create: '添加角色'
      },
      dialogRolesVisible: false,
      ruleTemp: {
        id: undefined,
        rules: []
      },
      selectRuleList: [],
      ruleList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getList()
    this.getRuleList()
  },
  methods: {
    getList() {
      this.listLoading = true
      request({
        url: '/role/list',
        data: this.listQuery
      }).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        roleName: '',
        tag: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.status = this.temp.status ? 1 : 0
          request({
            url: '/role/add',
            data: this.temp
          }).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        } else {
          this.$message({
            message: '请完善必填项',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleEdit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.status = this.temp.status ? 1 : 0
          request({
            url: '/role/edit',
            data: this.temp
          }).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        } else {
          this.$message({
            message: '请完善必填项',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$msgbox.confirm(
        '确认删除？',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        request({
          url: '/role/delete',
          data: { id: id }
        }).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleClose() {
      this.$refs.ruleTree.setCheckedKeys([])
      this.dialogRolesVisible = false
    },
    getRuleList() {
      request({
        url: '/rule/selectList'
      }).then(response => {
        this.ruleList = response.data
      })
    },
    handleAssign(row) {
      this.ruleTemp.id = row.id
      this.dialogRolesVisible = true
      // 获取选中角色所拥有的权限
      request({
        url: '/rule/getRulesByRoleID',
        data: { id: row.id }
      }).then(response => {
        this.selectRuleList = response.data
      })
    },
    assignRules() {
      // 获取选中权限
      this.ruleTemp.rules = [].concat(
        this.$refs.ruleTree.getCheckedKeys(), // 选中节点
        this.$refs.ruleTree.getHalfCheckedKeys() // 半选节点
      )

      request({
        url: '/role/assignRules',
        data: this.ruleTemp
      }).then(() => {
        this.$message({
          message: '分配成功',
          type: 'success',
          duration: 2000
        })
        this.dialogRolesVisible = false
      })
    }
  }
}
</script>
